import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from user.models import User
from utils.MyJwt import myjwt


class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get("HTTP_AUTHORIZATION", None)
        if token:
            try:
                tokendata = token.split(" ")[1]
                result = myjwt.checktoken(tokendata)
                user = User.objects.get(pk=result['id'])
                return (user, token)
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed("token过期")
            except jwt.InvalidTokenError:
                raise AuthenticationFailed("token无效")
            except:
                pass

myauthenta = MyAuthentication()
